<template>
  <a-drawer
    :width="500"
    :mask-closable="false"
    :visible="dataModel.visible"
    unmount-on-close
    ok-text="保存"
    :ok-loading="loading"
    @ok="handleOk"
    @cancel="handleCancel">
    <template #title>
      {{ dataModel.title }}
    </template>
    <div>
      <a-button type="primary" @click="addItem">
        <template #icon>
          <icon-plus />
        </template>
        添加项
      </a-button>
      <a-table :columns="tbColumns" :data="tbData" :pagination="false" style="margin-top: 20px"/>
    </div>
  </a-drawer>
</template>

<script setup lang="tsx">
import useDataModel from '@/hooks/data-model'
import useLoading from '@/hooks/loading'
import { Operation } from '@/types/global'
import { ref } from 'vue'
import { DictItemVo } from '@/types/modules/system'
import { addItem as addDictItem, findAllItemByDictId } from '@/api/modules/system/dict'
import { Message } from '@arco-design/web-vue'

const tbData = ref<DictItemVo[]>()
const tbColumns = [
  {
    title: '字典名',
    render: ({ rowIndex }: { record: any }) => {
      return <>
        <a-input v-model={tbData.value[rowIndex].name} />
      </>
    }
  }, {
    title: '字典值',
    render: ({ rowIndex }: { record: any }) => {
      return <>
        <a-input v-model={tbData.value[rowIndex].value} />
      </>
    }
  }, {
    title: '操作',
    render: ({ record, rowIndex }: { record: any }) => {
      return <>
        <a-popconfirm content={`确定删除 '${record.value || ''}' 吗?`} type="warning" onOk={() => removeItem(rowIndex)}>
          <a-button type="text" size="small" status="danger">
            删除
          </a-button>
        </a-popconfirm>
      </>
    }
  }
]


const dictId = ref<number>(-1)
const { dataModel, openModel, closeModel } = useDataModel();
const { loading, setLoading } = useLoading();

const handleCancel = () => {
  closeModel();
  setLoading(false);
};


const openHandle = async (code: string, id: number) => {
  dictId.value = id
  tbData.value = (await findAllItemByDictId(id)).data
  openModel(`${code}字典项`, false, true, Operation.UPDATE);
}

const addItem = () => {
  if (tbData.value?.length === 0 || (tbData.value[tbData.value?.length - 1].value && tbData.value[tbData.value?.length - 1].name)) {
    tbData.value?.push({})
  }
}

const removeItem = (index: number) => {
  tbData.value?.splice(index, 1)
}


const handleOk = async () => {
  try {
    setLoading(true)
    await addDictItem(dictId.value, tbData.value)
    Message.success({
      content: "保存成功",
      duration: 2000
    });
  } finally {
    setLoading(false)
  }
};

defineExpose({ openHandle });
</script>

<script lang="tsx">
export default {
  name: 'DictItemDrawer'
}
</script>

<style scoped>

</style>
